package com.teach;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <pre>
 * - UDP的接收端
 * Author : J.L.Zhou
 * E-Mail : 2233875735@qq.com
 * Tel : 151 1104 7708
 * Date : 2021-4-29 15:09:40
 * Version : 1.0
 * Copyright 2021 jlzhou.top Inc. All rights reserved.
 * Warning: this content is only for internal circulation of the company.
 *          It is forbidden to divulge it or use it for other commercial purposes.
 * </pre>
 */
public class UDPReceiver {

	public static void main(String[] args) {
		int port = 18000;
		DatagramSocket socket = null;
		try {
			socket = new DatagramSocket(port);
		} catch (SocketException e) {
			System.out.println("端口被占用了");
			e.printStackTrace();
		}
		System.out.println("创建完UDP的接收端");
		
		byte[] arr = new byte[65536];
		// 数据包的 大小 <=64k
		System.out.println(1024*64);
		DatagramPacket packet = new DatagramPacket(arr, 65536);
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS - ");
		
		while(true){
			try{
				System.out.println(format.format(new Date())+"准备接收包。");
				socket.receive(packet);//阻塞的接收包的方法
				// 从包中将数据取出
				byte[] arr1 = packet.getData();
				int len = packet.getLength();//得到包的具体长度
				InetAddress ip = packet.getAddress();//发送包的ip地址
				String str = new String(arr1, 0, len);
				System.out.println(format.format(new Date())+packet.getAddress().getHostAddress()+":"+str);
			}catch(Exception ex){
				break;
			}
		}

		// 4
		socket.close();
	}
}